<template>
  <view class="container">
    <!-- picker用法： https://uniapp.dcloud.net.cn/component/picker.html -->
    <picker mode="selector" :value="pick" :range="range" @change="bindTimeChange">
      <view class="timer">{{ formattedTime }}</view>
    </picker>

    <view class="controls">
      <button @click="startTimer" :disabled="isRunning">开始</button>
      <button @click="pauseTimer" :disabled="!isRunning">暂停</button>
      <button @click="resetTimer">重置</button>
    </view>
    <view class="status">{{ status }}</view>

  </view>
</template>

<script setup>
  import { computed, reactive, ref, nextTick } from 'vue';
  import { onHide, onShow } from "@dcloudio/uni-app"

  const range = reactive([5, 10, 15, 20, 25, 30, 35, 40, 45, 50])
  const pick = ref(0)
  const time = ref(5 * 60)
  const isRunning = ref(false)
  const status = ref('准备开始')

  let timer = null // 不需要响应式

  const formattedTime = computed(() => {
    const minutes = Math.floor(time.value / 60);
    const seconds = time.value % 60;
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`; // ${变量} 字符串  ${变量}
  })

  onHide(() => {
    pauseTimer()
    status.value = "你切出去玩手机了，必须重新开始计时"
  })

  onShow(() => {

  })

  const startTimer = () => {
    if (!isRunning.value) {
      isRunning.value = true;
      status.value = '工作中...';

      // setInterval(回调，计时器)
      timer = setInterval(() => {
        if (time.value > 0) {
          time.value--;
        } else {
          this.resetTimer();
          status.value = '时间到！休息一下吧！';
        }
      }, 1000);
    }
  }
  const pauseTimer = () => {
    if (isRunning.value) {
      isRunning.value = false;
      clearInterval(timer);
      status.value = '已暂停';
    }
  }
  const resetTimer = () => {
    isRunning.value = false;
    clearInterval(timer);
    time.value = pick.value * 60;
    status.value = '准备开始';
  }
  const bindTimeChange = (e) => {
    console.log(e.detail)
    pick.value = range[e.detail.value] ?? 5 // ?? 之前的值如果undefined 则 使用 ?? 后面的值
    time.value = pick.value * 60
  }
</script>

<style>
  .container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
  }

  .timer {
    font-size: 48px;
    margin-bottom: 20px;
  }

  .controls button {
    margin: 5px;
    padding: 10px 20px;
    font-size: 16px;
  }

  .status {
    margin-top: 20px;
    font-size: 20px;
    color: #666;
  }
</style>